package com.example.servicelifecycle;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 服务绑定后的操作
            Log.i("MainActivity", "onServiceConnected()被调用");
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 服务解绑后的操作
            Log.i("MainActivity", "onServiceDisconnected()被调用");
        }
    };

    public void onClick(View view) {
        int id = view.getId();
        Intent intent = new Intent(this, LifecycleService.class);
        if (id == R.id.btn_start) {
            startService(intent);
        } else if (id == R.id.btn_stop) {
            stopService(intent);
        } else if (id == R.id.btn_bind) {
            bindService(intent, connection, BIND_AUTO_CREATE);
        } else if (id == R.id.btn_unbind) {
            unbindService(connection);
        }
    }
}